/*
*    FileName: searchtimeset.cpp
*      Encode: GB2312 or system(on windows)
* Description: 检索某天某段时间某个摄像头的视频
*     Version: 1.0
*      Author: wulin
* Modification History

*/

#include "searchtimeset.h"
#include "ui_searchtimeset.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QDebug>
#include "realplay.h"

/*
构造函数，主要用于获得数据库中存储的数据的时间范围，并且用来设置dateEdit的日期范围
*/
SearchTimeSet::SearchTimeSet(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SearchTimeSet)
{
    ui->setupUi(this);
    rowRate=25;
    flagForComboBoxChange=false;
    //将QSqlQuery指向数据库连接“cFromPlayer",这条连接由RealPlay的一个成员函数建立
     queryOfSerch=new QSqlQuery(QSqlDatabase::database("cFromPlayer"));
     queryOfSerch2=new QSqlQuery(QSqlDatabase::database("cFromPlayer"));

     if(!queryOfSerch->exec("select min(DateTimeStart),max(DateTimeStart) from multidataindex"))
         qDebug()<<"select min(DateTimeStart),max(DateTimeStart)fail"<<queryOfSerch->lastError();
     else
     {
         if(queryOfSerch->next())
         {
             ui->dateEdit->setMinimumDate(queryOfSerch->value(0).toDateTime().date());
             ui->dateEdit->setMaximumDate(queryOfSerch->value(1).toDateTime().date());
         }
     }
     ui->comboBoxValidBegin->setCurrentIndex(-1);
     ui->comboBoxValidEnd->setCurrentIndex(-1);
 }

/*
槽函数，单击确定后，调用该函数。将用户最后选定的时间范围值赋给RealPlay的成员变量。

*/
void SearchTimeSet::on_buttonBox_accepted()
{
    updateTableName();

    on_timeEditEnd_editingFinished();

     *(((RealPlay*)parent())->playB)=ui->timeEditBegin->time();
     *(((RealPlay*)parent())->playE)=ui->timeEditEnd->time();

     if(ui->timeEditBegin->time().secsTo(ui->timeEditEnd->time())>0)
     ((RealPlay*)parent())->newPlayBack=true;
}

/*
更新表名。根据用户选择的日期和摄像头名，计算出表格的名字
*/
void SearchTimeSet::updateTableName()
{
    bool ok;
    QString tableNamePrefix=ui->dateEdit->date().toString("'multi'yyyy_MM_dd_'mac'").toAscii();
    if(queryOfSerch->exec("select NodeMacAddress from NodeAddressMap "
          "where NodeName='"+ui->comboBoxNodeName->currentText()+"'"))
    {
        if(queryOfSerch->next())
        {
            tableNameForHistory=tableNamePrefix+QString::number(queryOfSerch->value(0).toULongLong(&ok),10);
        }
        else
            qDebug()<<"Failure in SearchTimeSet::updateTableName:no NodeMacAddress match nodeName";
    }
    else
        qDebug()<<"select NodeMacAddress fail"<<queryOfSerch->lastError();
}

/*
 槽函数，在timeEditEnd的编辑结束（比如失去了焦点）时，调用该槽函数。
 主要用于检查其中的值是不是合理。
 */
void SearchTimeSet::on_timeEditEnd_editingFinished()
{
    //检查是否结束时间大于开始时间
    if(ui->timeEditEnd->time()<=ui->timeEditBegin->time())
    {
        QMessageBox::warning(this,tr("警告"),tr("结束时间应大于开始时间"));
        ui->timeEditEnd->setTime(ui->timeEditBegin->time());
    }

    //检查最后的时间范围有没有在有效时间范围外
    if(ui->timeEditBegin->time()<QTime::fromString(ui->comboBoxValidBegin->currentText()))
    {
        ui->timeEditBegin->setTime(QTime::fromString(ui->comboBoxValidBegin->currentText()));
    }
    else if(ui->timeEditEnd->time()>QTime::fromString(ui->comboBoxValidEnd->currentText()))
    {
        ui->timeEditEnd->setTime(QTime::fromString(ui->comboBoxValidEnd->currentText()));
    }
}

/*
更新comboBoxValidBegin和comboBoxValidEnd。根据用户选择的日期和摄像头，在这两个comboBox列出有效的时间范围。
另外，计算出rowRate，即每秒中，播放数据库中多少行数据。这是为了提高之后的检索速度，根据这个
值可以计算出某个时间对应的数据所在行的ID，这样就无需再根据非索引的时间来检索了。ID是多媒体表格的
主键，有很快的检索速度
*/
void SearchTimeSet::on_pushButtonRefresh_clicked()
{
    quint32 ID1,ID2,IDInterval(0),IDTemp;
    QTime timeB,timeE,timeTemp;
    QString newItem,newItemTemp;
    bool ok;
    ui->comboBoxValidBegin->clear();
    ui->comboBoxValidEnd->clear();
    validBeginVideoIDList.clear();

    updateTableName();
    if(queryOfSerch->exec("select DateTime,ID from "+tableNameForHistory+" where BeginEnd='b'"))
    {
        if(queryOfSerch->next()) //寻找到第一个系统头
        {
            timeB=queryOfSerch->value(0).toDateTime().time();
            newItem=timeB.toString("HH:mm:ss");
            ID1=queryOfSerch->value(1).toUInt(&ok);
            validBeginVideoIDList.append(ID1);
            ui->comboBoxValidBegin->addItem(newItem);
        }
        while(queryOfSerch->next()) //寻找其他的系统头
        {
            timeTemp=queryOfSerch->value(0).toDateTime().time();
            newItemTemp=timeTemp.toString("HH:mm:ss");
            IDTemp=queryOfSerch->value(1).toUInt(&ok);
            validBeginVideoIDList.append(IDTemp);
            ui->comboBoxValidBegin->addItem(newItemTemp);

            ID2=IDTemp-1;
            if(queryOfSerch2->exec("select DateTime from "+tableNameForHistory+
                               " where ID="+QString::number(ID2)) )
            {
                if(queryOfSerch2->next())
                {
                    timeE=queryOfSerch2->value(0).toDateTime().time();      
                    qint32 secs=timeE.secsTo(QTime(0,0,30,0));

                    if(secs>0&&timeB.secsTo(timeE)<0)
                        timeE=QTime(23,59,59,999);

                    newItem=timeE.toString("HH:mm:ss");

                    if(ID2-ID1>IDInterval)
                    {
                        IDInterval=ID2-ID1;
                        rowRate=IDInterval/(timeB.secsTo(timeE)+0.0);
                        if(rowRate<0)
                            rowRate=30;
                    }
                    ui->comboBoxValidEnd->addItem(newItem);
                }
            }
            else
                qDebug()<<"select fail in SearchTimeSet::on_pushButtonRefresh_clicked()";

            timeB=timeTemp;
            newItem=newItemTemp;
            ID1=IDTemp;
        } //所有系统头寻找结束，下面将寻找最后一行数据


        if(queryOfSerch->exec("select DateTime,ID,SensorID from "+tableNameForHistory+" where ID=("
         "select max(ID) from "+tableNameForHistory+")") )
        {
            if(queryOfSerch->next())
            {
                timeE=queryOfSerch->value(0).toDateTime().time();
                ID2=queryOfSerch->value(1).toUInt(&ok);
                qint32 secs=timeE.secsTo(QTime(0,0,30,0));

                if(secs>0&&timeB.secsTo(timeE)<0)
                    timeE=QTime(23,59,59,999);

                newItem=timeE.toString("HH:mm:ss");
                if(ID2-ID1>IDInterval)
                {
                    IDInterval=ID2-ID1;
                    rowRate=IDInterval/(timeB.secsTo(timeE)+0.0);
                    if(rowRate<0)
                        rowRate=-1*rowRate;
                }
                ui->comboBoxValidEnd->addItem(newItem);
            }
        }
        else
            qDebug()<<"select DateTime Fail in SearchTimeSet::on_pushButtonRefresh_clicked()";

    }
    else
        qDebug()<<"select fail in SearchTimeSet::on_pushButtonRefresh_clicked()"
                <<queryOfSerch->lastError();
}

/*
 槽函数，日期编辑框完成后，调用该函数。用于查找出该天有数据的摄像头的名字，列在comboBoxNodeName里
 */
void    SearchTimeSet::on_dateEdit_editingFinished()
{
    QString today,tomorrow;
    ui->comboBoxNodeName->clear();
    today=ui->dateEdit->date().toString("yyyyMMdd");
    tomorrow=ui->dateEdit->date().addDays(1).toString("yyyyMMdd");

    if(queryOfSerch->exec("select NodeName from nodeaddressmap where "
               "NodeMacAddress in (select NodeMacAddr from multidataindex where DateTimeStart >= "+
           today+" and DateTimeStart < "+tomorrow+")")  )
    {
        while(queryOfSerch->next())
        {
            ui->comboBoxNodeName->addItem(queryOfSerch->value(0).toString());
        }
    }
    else
        qDebug()<<queryOfSerch->lastError();
}

/*
下面两个函数用于保证，comboBoxValidBegin和comboBoxValidEnd两个框中显示的内容，始终是相同的index
*/
void SearchTimeSet::on_comboBoxValidBegin_currentIndexChanged(int index)
{
   // if(!flagForComboBoxChange)
    {
        ui->comboBoxValidEnd->setCurrentIndex(index);
        flagForComboBoxChange=true;
    }
   // else
        flagForComboBoxChange=false;

    ui->timeEditBegin->setTime(QTime::fromString(ui->comboBoxValidBegin->currentText()));
    validBeginVideoID=validBeginVideoIDList.at(index);

}
void SearchTimeSet::on_comboBoxValidEnd_currentIndexChanged(int index)
{
    //if(!flagForComboBoxChange)
    {
        ui->comboBoxValidBegin->setCurrentIndex(index);
        flagForComboBoxChange=true;
    }
   // else
        flagForComboBoxChange=false;
        ui->timeEditEnd->setTime(QTime::fromString(ui->comboBoxValidEnd->currentText()));
}



SearchTimeSet::~SearchTimeSet()
{
    delete ui;
}
